package ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import com.example.mynewsapp.R
import com.google.android.material.navigation.NavigationView

class MainFragment : Fragment(), NavigationView.OnNavigationItemSelectedListener {
    private var mDrawerLayout: DrawerLayout? = null


    // 配置drawer的点击事件
    // todo: drawer点击了没有改变底部导航的图标
    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        val whichItem = item.itemId
        when (whichItem) {
            R.id.drawer_nav_to_home -> {

                loadFragment(MainFragment())
            }

            R.id.drawer_nav_to_category -> {
                loadFragment(CategoryFragment())
            }

            R.id.drawer_nav_to_download -> {
                loadFragment(DownloadFragment())
            }

            R.id.drawer_nav_to_search -> {
                loadFragment(SearchFragment())
            }

            R.id.drawer_nav_to_setting -> {
                loadFragment(SettingFragment())
            }

            else -> {
                loadFragment(SettingFragment())
            }
        }
        mDrawerLayout!!.closeDrawer(GravityCompat.START)
        return true
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(
            R.layout.fragment_main,
            container, false
        )

        val toolbar: Toolbar = view.findViewById(R.id.toolbar)

        (activity as AppCompatActivity).setSupportActionBar(toolbar)
        (activity as AppCompatActivity).supportActionBar?.subtitle = "你好"

        val navigationView: NavigationView = view.findViewById(R.id.nav_view)
        // 配置Drawer
        mDrawerLayout = view.findViewById(R.id.drawer_layout)


        val toggle = ActionBarDrawerToggle(
            requireActivity(),
            mDrawerLayout,
            toolbar,
            // todo: Open Drawer
            R.string.app_name,
            // todo: Close Drawer
            R.string.app_name,
        )

        mDrawerLayout!!.addDrawerListener(toggle)

        toggle.syncState()
        navigationView.setNavigationItemSelectedListener(this)

        return view
    }


    private fun loadFragment(fragment: Fragment) {
        requireActivity().supportFragmentManager
            .beginTransaction()
            .replace(R.id.main_fragment, fragment)
            .commit()
    }

}